package com.imooc.bilibili.service;

import com.imooc.bilibili.dao.FileDao;
import com.imooc.bilibili.domain.File;
import com.imooc.bilibili.service.util.FastDFSUtil;
import io.netty.util.internal.StringUtil;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

@Service
public class FileService {
    @Autowired
    private FileDao fileDao;
    @Autowired
    private FastDFSUtil fastDFSUtil;

    public String uploadFileBySlices(MultipartFile slice, String fileMd5, Integer sliceNo, Integer totalSliceNo) throws IOException {
        File dbFileMd5 = fileDao.getFileByMD5(fileMd5);
        if (dbFileMd5 != null) {
            return dbFileMd5.getUrl();
        }
        String url = fastDFSUtil.uploadFileBySlices(slice, fileMd5, sliceNo, totalSliceNo);
        if (!StringUtil.isNullOrEmpty(url)) {
            dbFileMd5 = new File();
            dbFileMd5.setCreateTime(new Date());
            dbFileMd5.setMd5(fileMd5);
            dbFileMd5.setUrl(url);
            dbFileMd5.setType(fastDFSUtil.getFileType(slice));
            fileDao.addFile(dbFileMd5);
        }
        return url;
    }

    public String getFileMd5(MultipartFile file) throws IOException {
        InputStream is = file.getInputStream();
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int byteRead;
        while ((byteRead = is.read(buffer)) > 0) {
            bos.write(buffer, 0, byteRead);
        }
        is.close();
        return DigestUtils.md5Hex(bos.toByteArray());
    }
}
